package com.uxwine.alarm;


import android.content.Context;

public class Snooze
{
	Context mCtx;
	Settings.Snooze mSettings;
	private static final int TIMES_OF_TIMEOUT = 5;
	
	static Snooze mInstance;
	
	private Snooze(Context ctx)
	{
		mCtx = ctx;
		mSettings = new Settings.Snooze(mCtx);
	}
	
	public static synchronized Snooze getInstance(Context ctx)
	{
		if(null == mInstance)
			mInstance = new Snooze(ctx.getApplicationContext());
		return mInstance;
	}
	
	public Alarm getEnableAlarm()
	{
		if(isTimeout())
			return null;
		return getSnoozedAlarm();
	}
	
	public Alarm getSnoozedAlarm()
	{
		final int id = mSettings.getInt(Settings.Snooze.KEY_ID, -1);
		if(id == -1)
			return null;
		final long trigger = mSettings.getLong(Settings.Snooze.KEY_TRIGGER, -1);
		if(trigger == -1)
			return null;
		
		final Alarm a = AlarmDao.getAlarm(mCtx.getContentResolver(), id);
		if(null == a)
			return null;

		a.trigger = trigger;
		a.type = Alarm.ALARM_SNOOZE;
		return a;
	}
	
	public void saveSnoozeAlarm(final Alarm alarm)
	{
		if(null == alarm)
		{
			clear();
			return;
		}
		int times = mSettings.getInt(Settings.Snooze.KEY_TIME, -1);
		set(alarm.id, alarm.trigger, ++times);
	}	
	
	/**
	 * 将Snooze的trigger的清理掉。。
	 * @param id
	 */
	public void resetSnoozedAlarm(int id)
	{
		final int sid = mSettings.getInt(Settings.Snooze.KEY_ID, -1);
		if(sid != -1 && id == sid)
			mSettings.editor().remove(Settings.Snooze.KEY_TRIGGER).commit();
	}	
	
	public boolean isEnable(int id)
	{
		int sid = mSettings.getInt(Settings.Snooze.KEY_ID, -1);
		if(-1 == sid || id != sid)
			return true;
		return !isTimeout();
	}
	
	public boolean canSnoozed(int id)
	{
		int sid = mSettings.getInt(Settings.Snooze.KEY_ID, -1);
		if(-1 == sid || id != sid)
			return true;
		return mSettings.getInt(Settings.Snooze.KEY_TIME, 0) + 1 < TIMES_OF_TIMEOUT;
	}
	
	public boolean isSnoozed(int id)
	{
		int sid = mSettings.getInt(Settings.Snooze.KEY_ID, -1);
		if(sid == -1)
			return false;
		return (id == sid);
	}
	
	public boolean isTimeout()
	{
		final int times = mSettings.getInt(Settings.Snooze.KEY_TIME, 0);
		return times >= TIMES_OF_TIMEOUT;
	}
	
	public void set(int id, long trigger, int times)
	{
		mSettings.editor()
		.putInt(Settings.Snooze.KEY_ID, id)
		.putLong(Settings.Snooze.KEY_TRIGGER, trigger)
		.putInt(Settings.Snooze.KEY_TIME, times)
		.commit();
	}
	
	public void clear()
	{
		mSettings.editor()
		.remove(Settings.Snooze.KEY_ID)
		.remove(Settings.Snooze.KEY_TRIGGER)
		.remove(Settings.Snooze.KEY_TIME)
		.commit();
	}
}
